package com.lyy.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Liangyaoyun
 */
@Slf4j
@ControllerAdvice("com.lyy")
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validationException(MethodArgumentNotValidException e) {
        log.error("爆发异常，被GlobalExceptionHandler.validationException()捕获", e);
        BindingResult bindingResult = e.getBindingResult();
        // 判断bindingResult中是否存在校验失败的信息
        if (bindingResult.hasErrors()) {
            // 获取bindingResult中所有属性错误信息集合中的第一个属性错误
            FieldError firstFieldError = bindingResult.getFieldErrors().get(0);
            // 响应 "xxx实例的xxx属性校验失败: xxx异常信息"
            return
                            // 获取属性所在实例
                            firstFieldError.getObjectName() + "." +
                            // 获取属性名称
                            firstFieldError.getField() + "校验失败: " +
                            // 获取实体类中设置的错误信息字符串
                            firstFieldError.getDefaultMessage();
        }
        return e.getMessage();
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public String exception(Exception e) {
        log.error("爆发异常", e);
        return e.getMessage();
    }
}
